//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using System.Collections;

namespace CommunityServer.Controls
{
	public class Search : TemplatedWebControl
	{
		protected TextBox SearchBox = null;
		protected IButton SearchButton = null;
		protected CSContext csContext = CSContext.Current;

		#region Search Properties

		bool _readPropertiesFromContext = false;
		public bool ReadPropertiesFromContext
		{
			get { return _readPropertiesFromContext; }
			set { _readPropertiesFromContext = value; }
		}

		string _sectionIDsToSearch = null;
		public string SectionIDsToSearch
		{
			get	
			{ 
				if (ReadPropertiesFromContext && _sectionIDsToSearch == null && csContext.SectionID > 0)
					_sectionIDsToSearch = csContext.SectionID.ToString();

				return _sectionIDsToSearch; 
			}
			set	{ _sectionIDsToSearch = value; }
		}

		DateTime _startDate = DateTime.MinValue;
		public DateTime StartDate
		{
			get	{ return _startDate; }
			set	{ _startDate = value; }
		}

		DateTime _endDate = DateTime.MinValue;
		public DateTime EndDate
		{
			get	{ return _endDate; }
			set { _endDate = value; }
		}

		string _userNamesToSearch;
		public string UserNamesToSearch
		{
			get	{ return _userNamesToSearch; }
			set	{ _userNamesToSearch = value; }
		}

        string _categoriesToSearch;
        public string Tags
        {
            get { return _categoriesToSearch; }
            set { _categoriesToSearch = value; }
        }

		string _userIDsToSearch;
		public string UserIDsToSearch
		{
			get	
			{ 
				if (ReadPropertiesFromContext && _userIDsToSearch == null && csContext.UserID > 0)
					_userIDsToSearch = csContext.UserID.ToString();

				return _userIDsToSearch; 
			}
			set	{ _userIDsToSearch = value; }
		}

		string _applicationTypes;
		public string ApplicationTypes
		{
			get	{ return _applicationTypes; }
			set	{ _applicationTypes = value; }
		}

		string _groupIDsToSearch;
		public string GroupIDsToSearch
		{
			get	
			{ 
				if (ReadPropertiesFromContext && _groupIDsToSearch == null && csContext.GroupID > 0)
					_groupIDsToSearch = csContext.GroupID.ToString();

				return _groupIDsToSearch; 
			}
			set	{ _groupIDsToSearch = value; }
		}

		SearchSort _sortBy = SearchSort.Relevance;
		public SearchSort SortBy
		{
			get { return _sortBy; }
			set { _sortBy = value; }
		}

		#endregion

		protected override void AttachChildControls()
		{
			SearchBox = FindControl("SearchBox") as TextBox;
			SearchButton = FindButton("SearchButton");

			if(SearchButton != null)
			{
				SearchButton.Click +=new EventHandler(SearchButton_Click);
				SearchButton.Text = ResourceManager.GetString("SearchRedirect_SearchButton");
				SearchButton.CausesValidation = false;
			}

			if (!Page.IsPostBack)
			{
				string q = Context.Request.QueryString["q"];
				if(!Globals.IsNullorEmpty(q))
					SearchBox.Text = q;
			}
		}

		protected void SearchButton_Click(object sender, EventArgs e)
		{
			string searchText = SearchBox.Text;
			if(!Globals.IsNullorEmpty(searchText))
			{
				SearchQuery query = GetSearchQuery();				
				csContext.Context.Response.Redirect(Globals.GetSiteUrls().SearchForText(SearchProvider.Instance().SearchQueryString(query)));
			}
		}

		protected SearchQuery GetSearchQuery()
		{
			SearchQuery query = new SearchQuery();

			#region Populate the search query using the current search text and additional/optional properties

			EnsureChildControls();

			query.QueryText = SearchBox.Text;
			query.SortBy = this.SortBy;

			if (this.StartDate != DateTime.MinValue)
				query.StartDate = this.StartDate;

			if (this.EndDate != DateTime.MinValue)
				query.EndDate = this.EndDate;

			if (!Globals.IsNullorEmpty(this.SectionIDsToSearch))
			{
				ArrayList sections = new ArrayList();

				foreach (string sectionID in this.SectionIDsToSearch.Split(','))
				{
					if (!Globals.IsNullorEmpty(sectionID.Trim()))
						sections.Add(int.Parse(sectionID.Trim()));
				}

				if (sections.Count > 0)
					query.SectionsToSearch = (int[]) sections.ToArray(typeof(int));
			}

			if (!Globals.IsNullorEmpty(this.GroupIDsToSearch))
			{
				ArrayList groups = new ArrayList();

				foreach (string groupID in this.GroupIDsToSearch.Split(','))
				{
					if (!Globals.IsNullorEmpty(groupID.Trim()))
						groups.Add(int.Parse(groupID.Trim()));
				}

				if (groups.Count > 0)
					query.GroupsToSearch = (int[]) groups.ToArray(typeof(int));
			}

			if (!Globals.IsNullorEmpty(this.ApplicationTypes))
			{
				ArrayList appTypes = new ArrayList();

				foreach (string appType in this.ApplicationTypes.Split(','))
				{
					if (!Globals.IsNullorEmpty(appType.Trim()))
						appTypes.Add(Enum.Parse(typeof(ApplicationType), appType.Trim(), true));
				}

				query.ApplicationTypes = (ApplicationType[]) appTypes.ToArray(typeof(ApplicationType));
			}

			if (!Globals.IsNullorEmpty(this.UserIDsToSearch))
			{
				ArrayList userIDs = new ArrayList();

				foreach (string userID in this.UserIDsToSearch.Split(','))
				{
					if (!Globals.IsNullorEmpty(userID.Trim()))
						userIDs.Add(int.Parse(userID.Trim()));
				}

				query.UsersToSearch = (int[]) userIDs.ToArray(typeof(int));
			}

            if (!Globals.IsNullorEmpty(this.Tags))
            {
                ArrayList tags = new ArrayList();

                foreach (string tag in this.Tags.Split(','))
                {
                    if (!Globals.IsNullorEmpty(tag.Trim()))
                        tags.Add(tag.Trim());
                }

                query.Tags = (string[])tags.ToArray(typeof(string));
            }

			if (!Globals.IsNullorEmpty(this.UserNamesToSearch))
			{
				ArrayList userNames = new ArrayList();

				foreach (string userName in this.UserNamesToSearch.Split(','))
				{
					if (!Globals.IsNullorEmpty(userName.Trim()))
						userNames.Add(userName.Trim());
				}

				query.UserNamesToSearch = (string[]) userNames.ToArray(typeof(string));
			}

			#endregion

			return query;
		}
	}
}
